package com.credit.mola.app.utils.sysdata

import android.content.Context
import com.credit.mola.app.utils.sysdata.method.SysDataMethod6
import com.credit.mola.app.utils.sysdata.method.SysDataMethod2
import com.credit.mola.app.utils.sysdata.method.SysDataMethod1
import com.credit.mola.app.utils.sysdata.method.SysDataMethod3
import com.credit.mola.app.utils.sysdata.method.SysDataMethod5
import com.credit.mola.app.utils.sysdata.method.SysDataMethod4
import com.credit.mola.app.utils.sysdata.method.SysDataMethod7
import com.google.gson.Gson

class SysDataManager(val context: Context, val product: String, val token: String) {

    private fun formatToMode1(path: String, fetchData: () -> String?): String? {
        if (!formatJson(path)) return null
        val content = fetchData()?:""

        // TODO: 加密操作
//        val encrypted: String = AESCryptUtil.encryptDefault(content)
//        return encrypted
        return content
    }

    private fun formatToMode2(path: String, key: String, fetchData: () -> String?): String? {
        if (!formatJson(path)) return null
        val data = fetchData() ?: return null
        val params = baseJson(path).apply { put(key, data) }
        val content = Gson().toJson(params).trim()

        // TODO: 加密操作
//        val encrypted: String = AESCryptUtil.encryptDefault(content)
//        return encrypted
        return content
    }

    private fun formatJson(path: String) = listOf(product, token, path).all { it.isNotBlank() }

    private fun baseJson(path: String) = hashMapOf<String, Any>(
        "path" to path.replace("/", ""),
        "token" to token,
        "product" to product
    )

    fun getSysData1(path: String) = formatToMode1(path) {
        SysDataMethod1(context, product, token, path).getDataMethod()
    }

    fun getSysData7(path: String) = formatToMode1(path) {
        SysDataMethod7(context, product, token, path).getDataMethod()
    }

    fun getSysData3(path: String) = formatToMode2(path, "deviceHardwareGzip") {
        SysDataMethod3(context).getDataMethod()
    }

    fun getSysData2(path: String, onResult: (String?) -> Unit) {
        SysDataMethod2(context = context, onResult = { bd ->
            val result = formatToMode2(path, "deviceBatteryGzip") { bd }
            onResult.invoke(result)
        }).start()
    }

    fun getSysData5(path: String) = formatToMode2(path, "deviceWifiGzip") {
        SysDataMethod5(context).getDataMethod()
    }

    fun getSysData4(path: String) = formatToMode2(path, "deviceStorageGzip") {
        SysDataMethod4(context).getDataMethod()
    }

    fun getSysData6(path: String) = formatToMode2(path, "appListGzip") {
        SysDataMethod6(context).getDataMethod()
    }
}